package oa.hleast.xswl.utils;

import lombok.extern.slf4j.Slf4j;
import oa.hleast.xswl.common.config.NotBlank;
import oa.hleast.xswl.pojo.vo.IdCardVO;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 传入需要校验的实体类对象,检验必填参数是否为空或者null
 *
 * @author 302
 * @created 2020/7/28
 */
@Slf4j
public class ClassPropertyHandler<T> {

    private Field[] fields = new Field[]{};

    private T t;

    private Class clazz;

    public ClassPropertyHandler(T t) {
        this.t = t;
        this.fields = t.getClass().getDeclaredFields();
        this.clazz = t.getClass();
    }

    /**
     * 获取所有get方法 方法名
     *
     * @return
     */
    private List<String> getGetMethodName() {
        List<String> list = new ArrayList<>();
        for (Field field : fields) {
            //可自定义注解,标识必填字段
            Annotation annotation = field.getAnnotation(NotBlank.class);
            if (26 == field.getModifiers() || annotation == null) {
                continue;
            }
            char[] cs = field.getName().toCharArray();
            //首字母大写
            cs[0] -= 32;
            list.add("get" + String.valueOf(cs));
        }
        return list;
    }

    /**
     * 判断实体类属性值那些必填字段为空
     *
     * @return 返回空表示 必须有值的属性都满足需求 其他看返回值
     */
    public String hasNullOrEmptyPropertyValue() {
        String result = "";
        List<String> list = getGetMethodName();
        for (String methodName : list) {
            try {
                Method method = clazz.getMethod(methodName);
                Object res = method.invoke(t, null);
                if (res == null || "".equals(res)) {
                    //把 "get"截掉
                    String property = methodName.substring(3);
                    char[] chars = property.toCharArray();
                    //首字母变小写
                    chars[0] += 32;
                    result = result + ", " + String.valueOf(chars);
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        if ("".equals(result)) {
            return result;
        }
        return "参数: " + result.substring(2, result.length() - 1) + " 值为空或者null";
    }

    public static void main(String[] args) {

        IdCardVO idCardVO = IdCardVO.builder().build();
        String message = new ClassPropertyHandler<>(idCardVO).hasNullOrEmptyPropertyValue();
        log.info("message = {}", message);
    }
}